package com.toidep.fragment.others;

import android.content.Context;
import android.os.AsyncTask;
import android.os.Bundle;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.View.OnTouchListener;
import android.view.ViewGroup;
import android.view.inputmethod.EditorInfo;
import android.view.inputmethod.InputMethodManager;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.ImageView.ScaleType;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.TextView.OnEditorActionListener;

import com.toidep.R;
import com.toidep.activities.MainActivity;
import com.toidep.adapters.CommentAdapter;
import com.toidep.api.ApiController;
import com.toidep.api.ParseJSON;
import com.toidep.base.BaseFragment;
import com.toidep.config.ConfigUtility;
import com.toidep.config.Constants;
import com.toidep.entities.ModelEntity;
import com.toidep.interfaces.DialogListener;
import com.toidep.interfaces.ResponseListener;
import com.toidep.preference.SharePreference;
import com.toidep.utilities.DatetimeUtil;
import com.toidep.utilities.DialogUtility;
import com.toidep.widgets.sectionlist.AmazingListView;

public class ModelDetailFragment extends BaseFragment implements OnClickListener {

	private MainActivity mainActivity;
	
	private View view;
	private AmazingListView amazingListView;
	private CommentAdapter amazingAdapter;
	
	private String model_id = "";
	private ModelEntity modelEntity;
	private EditText edtComment;
	
	public void setValues(String model_id) {
		this.model_id = model_id;
	}
	
	/**
	 * Set lai cac base value cho fragment: cac item cua thanh header, currentCategory cua menuSideBar
	 */
	public void setBaseValues() {
		mainActivity.currentCategory = Constants.CATEGORY_MODEL;
		mainActivity.mainFragment.setTittle(mainActivity.getString(R.string.label_category_model));
		mainActivity.mainFragment.showButtonSlide(false);
	}
	
	@Override
	public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {

		view = inflater.inflate(R.layout.fragment_model_detail, container, false);

		mainActivity = (MainActivity) getActivity();

		initComponents();
		
		requestData();

		setBaseValues();
		
		return view;
	}

	private ImageView modelImage;
	private TextView modelName, modelBirthday, txv_total_comments;
	private RelativeLayout layout_detail_album, layout_detail_video, layout_detail_profile, layout_detail_news, layout_detail_relative; //
	private ImageView imageview_album, imageview_video, imageview_play, imageview_profile, imageview_news, imageview_relative; // 
	private LinearLayout layoutLoading;
	
	@Override
	public void onResume() {
		// TODO Auto-generated method stub
		super.onResume();
		boolean loginStatus = SharePreference.getInstance(mainActivity)
				.getLoginStatus();
		if (loginStatus) {
			edtComment.setText("");
			
		} else {
			edtComment.setText("Đề nghị login để bình luận");
		}
	}
	private void initComponents() {
		layoutLoading = (LinearLayout) view.findViewById(R.id.layoutLoading);
		layoutLoading.setVisibility(View.VISIBLE);
		
		modelImage = (ImageView) view.findViewById(R.id.modelImage);
		modelName = (TextView) view.findViewById(R.id.modelName);
		modelBirthday = (TextView) view.findViewById(R.id.modelBirthday);
		layout_detail_album = (RelativeLayout) view.findViewById(R.id.layout_detail_album);
		layout_detail_album.setOnClickListener(this);
		layout_detail_video = (RelativeLayout) view.findViewById(R.id.layout_detail_video);
		layout_detail_video.setOnClickListener(this);
		layout_detail_profile = (RelativeLayout) view.findViewById(R.id.layout_detail_profile);
		layout_detail_profile.setOnClickListener(this);
		layout_detail_news = (RelativeLayout) view.findViewById(R.id.layout_detail_news);
		layout_detail_news.setOnClickListener(this);
		layout_detail_relative = (RelativeLayout) view.findViewById(R.id.layout_detail_relative);
		layout_detail_relative.setOnClickListener(this);
		
		imageview_album = (ImageView) view.findViewById(R.id.imageview_album);
		imageview_video = (ImageView) view.findViewById(R.id.imageview_video);
		imageview_play = (ImageView) view.findViewById(R.id.imageview_play);
		imageview_profile = (ImageView) view.findViewById(R.id.imageview_profile);
		imageview_news = (ImageView) view.findViewById(R.id.imageview_news);
		imageview_relative = (ImageView) view.findViewById(R.id.imageview_relative);
		
		txv_total_comments = (TextView) view.findViewById(R.id.txv_total_comments);
		
		edtComment = (EditText) view.findViewById(R.id.edtComment);
//		edtComment.setOnKeyListener(new OnKeyListener() {
//
//			@Override
//			public boolean onKey(View v, int keyCode, KeyEvent event) {
//				// TODO Auto-generated method stub
//				if (keyCode == KeyEvent.KEYCODE_ENTER && event.getAction() == KeyEvent.ACTION_UP) {
//					postComment();
//
//					return true;
//				}
//				return false;
//			}
//		});
		
		edtComment.setImeOptions(EditorInfo.IME_ACTION_DONE);
		edtComment.setOnEditorActionListener(new OnEditorActionListener() {
			
			@Override
			public boolean onEditorAction(TextView v, int actionId, KeyEvent event) {
					postComment();
				return true;
			}
		});
		
	edtComment.setOnTouchListener(new OnTouchListener() {
			
			@Override
			public boolean onTouch(View v, MotionEvent event) {
				if(event.getAction() == MotionEvent.ACTION_DOWN){
					if(!mainActivity.checkUserLogon()){
						return true;
					}
				}
				return false;
			}
		});
	}
	
	public static ModelDetailFragment newInstance(String modelId) {
		ModelDetailFragment myFragment = new ModelDetailFragment();
		myFragment.model_id = modelId;
		
		return myFragment;
	}
	
	/**
	 * Goi API get list models
	 */
	private void requestData() {
		// Lay thong tin chi tiet cua Nguoi mau
		ApiController.getModelDetail(mainActivity, model_id, new ResponseListener() {
			@Override
			public void processResponse(int inintstall) {
				// TODO Auto-generated method stub
				
			}
			
			@Override
			public void processResponse(String response) {
				processData(response);
			}
		});
	}
	
	private void processData(String response) {
		AsyncTask<String, String, ModelEntity> asyn = new AsyncTask<String, String, ModelEntity>() {

			@Override
			protected ModelEntity doInBackground(String... params) {
				if (params[0] != null) {
					ModelEntity modelEntity = ParseJSON.getModelObjectFromResponse(params[0]);
					return modelEntity;
				}
				return null;
			}
			
			@Override
			protected void onPostExecute(ModelEntity modelEntity) {
				setWidgetInfo(modelEntity);
			}
			
		};
		
		asyn.execute(response);
	}
	
	protected void setWidgetInfo(ModelEntity modelEntity) {
		layoutLoading.setVisibility(View.GONE);
		this.modelEntity = modelEntity;
		
		// anh Top
		int widthImage = ConfigUtility.size_full_width;
		int heightImage = (int) (widthImage * ConfigUtility.scale_size_top_image);
		
		int widthImageView = ConfigUtility.scrWidth;
		int heightImageView = (int) (widthImageView * ConfigUtility.scale_size_top_image);
		
		LinearLayout.LayoutParams param1 = new LinearLayout.LayoutParams(widthImageView, heightImageView);
		
		modelImage.setLayoutParams(param1);
		modelImage.setScaleType(ScaleType.FIT_XY);
		mainActivity.loadImage(modelImage, modelEntity.getBackground(), widthImage, heightImage, widthImageView, heightImageView);

		// anh Menu
		int widthImage2 = ConfigUtility.size_half_width;
		int heightImage2 = (int) (widthImage2 * ConfigUtility.scale_size_horizontal_thumbs_item);
		
		int widthImageView2 = ConfigUtility.scrWidth*2/7;
		int heightImageView2 = (int) (widthImageView2 * ConfigUtility.scale_size_horizontal_thumbs_item);
		
		RelativeLayout.LayoutParams param2 = new RelativeLayout.LayoutParams(widthImageView2, heightImageView2);
		RelativeLayout.LayoutParams param3 = (RelativeLayout.LayoutParams) imageview_play.getLayoutParams();
		param3.width = widthImageView2/4;
		param3.height = widthImageView2/4*37/48;
		imageview_play.setLayoutParams(param3);
		imageview_play.setScaleType(ScaleType.FIT_XY);
		
		// button Album
		imageview_album.setLayoutParams(param2);
		imageview_album.setScaleType(ScaleType.FIT_XY);
		mainActivity.loadImage(imageview_album, modelEntity.getIcon(), widthImage2, heightImage2, widthImageView2, heightImageView2);
		
		// button Video		
		imageview_video.setLayoutParams(param2);
		imageview_video.setScaleType(ScaleType.FIT_XY);
		mainActivity.loadImage(imageview_video, modelEntity.getIcon(), widthImage2, heightImage2, widthImageView2, heightImageView2);

		// button Profile
		imageview_profile.setLayoutParams(param2);
		imageview_profile.setScaleType(ScaleType.FIT_XY);
		
		// button News
		imageview_news.setLayoutParams(param2);
		imageview_news.setScaleType(ScaleType.FIT_XY);

		// button Relative
		imageview_relative.setLayoutParams(param2);
		imageview_relative.setScaleType(ScaleType.FIT_XY);
		
		modelName.setText(modelEntity.getName());
		
		String birthday = DatetimeUtil.convertTimestampToString(modelEntity.getBirthday());
		modelBirthday.setText(birthday);
		txv_total_comments.setText(modelEntity.getTotalComment());

		// Khoi tao list
		amazingListView = (AmazingListView) view.findViewById(R.id.amazingListView);
		amazingListView.setAdapter(amazingAdapter = new CommentAdapter(this, Constants.CATEGORY_MODEL_DETAL, Constants.COMMENT_TYPE_MODEL, modelEntity.getId()));
		amazingListView.setLoadingView(getActivity().getLayoutInflater().inflate(R.layout.layout_loading_view, null));
		amazingAdapter.setAmazingListView(amazingListView, ConfigUtility.PAGE_SIZE);
		amazingAdapter.notifyMayHaveMorePages();
		
		amazingAdapter.resetList();
	}

	@Override
	public void onClick(View v) {
		switch (v.getId()) {
		case R.id.layout_detail_album:
			ModelDetailAlbumFragment albumFragment = ModelDetailAlbumFragment.newInstance();
			albumFragment.setValues(modelEntity);
			albumFragment.setBackView(false);
			mainActivity.mainFragment.openFragmentScreen(albumFragment, null);
			break;
		case R.id.layout_detail_video:
			ModelDetailVideoFragment videoFragment = ModelDetailVideoFragment.newInstance();
			videoFragment.setValues(modelEntity);
			videoFragment.setBackView(false);
			mainActivity.mainFragment.openFragmentScreen(videoFragment, null);
			break;
		case R.id.layout_detail_profile:
			ModelDetailProfileFragment profileFragment = ModelDetailProfileFragment.newInstance();
			profileFragment.setValues(modelEntity);
			profileFragment.setBackView(false);
			mainActivity.mainFragment.openFragmentScreen(profileFragment, null);
			break;
		case R.id.layout_detail_news:
			mainActivity.openSearchFragmen(modelEntity.getName(), Constants.TAB_VIEW_SEARCH_NEWS, true);
			break;
		case R.id.layout_detail_relative:
			ModelDetailRelationFragment relationFragment = ModelDetailRelationFragment.newInstance();
			relationFragment.setValues(modelEntity);
			relationFragment.setBackView(false);
			mainActivity.mainFragment.openFragmentScreen(relationFragment, null);
			break;
		}
		
	}
	public void postComment() {
		String comment = edtComment.getText().toString();
		if (comment != null && comment.length() > 0) {
			mainActivity.postComment(Constants.COMMENT_TYPE_MODEL, model_id, comment, new ResponseListener() {
				
				@Override
				public void processResponse(int inintstall) {
					// TODO Auto-generated method stub
					
				}
				
				@Override
				public void processResponse(String response) {
					 boolean resultPostComment = ParseJSON.getResultPostCommentFromResponse(response);
					 if (resultPostComment) {
						 edtComment.setText("");
//						 isRequestCommentData = false;
						 requestData();
					 }
				}
			});
		} else {
			DialogUtility.showDialogAlert(mainActivity, null, getString(R.string.text_empty_comment), getString(R.string.label_close),
				new DialogListener() {
					public void after() {
						showKeyBoard(edtComment);
					}
				});
		}
		InputMethodManager imm = (InputMethodManager)getActivity().getSystemService(
			      Context.INPUT_METHOD_SERVICE);
		imm.hideSoftInputFromWindow(edtComment.getWindowToken(), 0);
	}
	public void showKeyBoard(EditText editText) {
		if (editText != null) {
			editText.setFocusable(true);
			editText.setFocusableInTouchMode(true);
			editText.requestFocus();
			InputMethodManager inputMethodManager = ((InputMethodManager) mainActivity.getSystemService(Context.INPUT_METHOD_SERVICE));
			inputMethodManager.showSoftInput(editText, 1);
		}
	}
	public void refresh() {
		if (amazingAdapter != null) {
			amazingAdapter.clear();
		}

		removeAllViews();
		
		requestData();
	}

	public void removeAllViews() {
		if (modelName != null) modelName.setText("");
		if (modelBirthday != null) modelBirthday.setText("");
		if (txv_total_comments != null) txv_total_comments.setText("");
	}
}
